package com.cyz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyz.dao.HealthDao;
import com.cyz.dao.OldDao;
import com.cyz.dao.UserDao;
import com.cyz.entity.Doctor;
import com.cyz.entity.Health;
import com.cyz.entity.Old;
import com.cyz.entity.User;
import com.cyz.vo.HealthDTO;
import com.cyz.vo.OldImgDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;

@RestController
@RequestMapping("/old")
public class OldInfoController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private HealthDao healthDao;

    @Autowired
    private OldDao oldDao;

    @PostMapping("/getHealthByAccount/{account}")
    public HealthDTO getDocByAccount(@PathVariable String account){
        User user = userDao.selectOne(new QueryWrapper<User>().eq("account", account));

        String name = user.getName();
        Health health = healthDao.selectOne(new QueryWrapper<Health>().eq("name", name));

        HealthDTO healthDTO = new HealthDTO();
        BeanUtils.copyProperties(health, healthDTO);

        healthDTO.setHealth(oldDao.selectOne(new QueryWrapper<Old>().eq("name", name)).getHealth());

        return healthDTO;
    }

    @PostMapping("/getOldByAccount/{account}")
    public OldImgDTO getOldByAccount(@PathVariable String account){
        User user = userDao.selectOne(new QueryWrapper<User>().eq("account", account));

        Old old = oldDao.selectOne(new QueryWrapper<Old>().eq("name", user.getName()));

        OldImgDTO oldImgDTO = new OldImgDTO();
        BeanUtils.copyProperties(old, oldImgDTO);
        String url = null;
        String base64 = Base64.getEncoder().encodeToString(old.getImg());

        // Construct the URL for the img tag with the data URI scheme
        url = "data:image/jpeg;base64," + base64;

        oldImgDTO.setUrl(url);

        return oldImgDTO;
    }

    @PostMapping("/updateOld")
    public String updateDoc(Old old){
        int update = oldDao.update(old, new QueryWrapper<Old>().eq("id", old.getId()));
        return update == 0 ? "更新失败" : "更新成功";
    }
}
